package cn.afactory.tygz.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.harwkin.nb.camera.BaseImgView;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.afactory.tygz.R;
import cn.afactory.tygz.TianYaGongZaiApplication;
import cn.afactory.tygz.common.MsgType;
import cn.afactory.tygz.model.MessageDetail;
import cn.afactory.tygz.ui.base.utils.DateUtil;
import cn.afactory.tygz.ui.base.utils.HarwkinLogUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.view.GifTextView;

/**
 * Created with Android Studio.
 * Title:PrivateMessageAdapter
 * Description:
 * Copyright:Copyright (c) 2015
 * Company:和平必胜、正义必胜、人民必胜
 * Author:炎黄子孙
 * Date:15/9/23
 * Time:下午2:00
 * Version 1.0
 */
public class PrivateMessageAdapter extends BaseAdapter{
    public static final Pattern EMOTION_URL = Pattern.compile("\\[(\\S+?)\\]");

    private Context mContext;
    private LayoutInflater mInflater;
    private List<MessageDetail> mMsgList;
    private String mUserIcon;
    public PrivateMessageAdapter(Context context, List<MessageDetail> msgList,String userIcon) {
        this.mContext = context;
        mMsgList = msgList;
        mUserIcon = userIcon;
        mInflater = LayoutInflater.from(context);
    }

    public void setDatas(List<MessageDetail> list){
        mMsgList = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mMsgList.size();
    }

    @Override
    public Object getItem(int position) {
        return mMsgList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextMessageHolder holder = null;
        HarwkinLogUtils.getInstance().info("type = " + mMsgList.get(position).type + " , msg = " + mMsgList.get(position).msg);
//        if (null == convertView) {
//            holder = new TextMessageHolder();
//            if(mMsgList.get(position).type == MsgType.SEND){
//                convertView = mInflater.inflate(
//                        R.layout.item_private_message_self_list, null, false);
//            }else if(mMsgList.get(position).type == MsgType.REV){
//                convertView = mInflater.inflate(
//                        R.layout.item_private_message_other_list, null, false);
//            }
//            holder.userIcon = (ImageView) convertView.findViewById(R.id.iv_user_icon);
//            holder.msgDate = (TextView) convertView.findViewById(R.id.tv_msg_date);
//            holder.rlMsg = (RelativeLayout) convertView.findViewById(R.id.rl_msg_content);
//            holder.msg = (GifTextView) convertView.findViewById(R.id.tv_msg_content);
//            convertView.setTag(holder);
//        } else {
//            holder = (TextMessageHolder) convertView.getTag();
//        }

        holder = new TextMessageHolder();
        if(mMsgList.get(position).type == MsgType.SEND){
            convertView = mInflater.inflate(
                    R.layout.item_private_message_self_list, null, false);
        }else if(mMsgList.get(position).type == MsgType.REV){
            convertView = mInflater.inflate(
                    R.layout.item_private_message_other_list, null, false);
        }
        holder.userIcon = (ImageView) convertView.findViewById(R.id.iv_user_icon);
        holder.msgDate = (TextView) convertView.findViewById(R.id.tv_msg_date);
        holder.rlMsg = (RelativeLayout) convertView.findViewById(R.id.rl_msg_content);
        holder.msg = (GifTextView) convertView.findViewById(R.id.tv_msg_content);

        MessageDetail mItem = mMsgList.get(position);
        handleTextMessage(holder, mItem, parent);
        return convertView;
    }

    private void handleTextMessage(final TextMessageHolder holder,
                                   final MessageDetail mItem, final View parent) {
        handleBaseMessage(holder, mItem);

        // 文字
        holder.msg.insertGif(convertNormalStringToSpannableString(mItem.msg + " "));
    }

    private void handleBaseMessage(MessageHolderBase holder,
                                   final MessageDetail mItem) {
        holder.msgDate.setText(DateUtil.getCreateAt(new Date(mItem.addTime)));
        holder.msgDate.setVisibility(View.VISIBLE);
        String userIcon = mItem.userIcon;
        if(mItem.type == MsgType.SEND) {
            if (SPUtils.isSelf(mContext, mItem.userId)) {
                userIcon = SPUtils.getUserIcon(mContext);
            }
        }else if(mItem.type == MsgType.REV){
            userIcon = mUserIcon;
        }
        if (userIcon != null) {
            BaseImgView.loadimg(holder.userIcon,
                    userIcon,
                    R.drawable.ic_pic_loading_default_small,
                    R.drawable.ic_pic_loading_default_small,
                    R.drawable.ic_pic_loading_default_small,
                    ImageScaleType.EXACTLY,
                    (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30),
                    (int) mContext.getResources().getDimension(R.dimen.healthcircle_padding30), 0);
        } else {
            holder.userIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_pic_loading_default_small));
        }

        holder.userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!SPUtils.isSelf(mContext,mItem.userId)) {
                    NaviUtils.gotoUserProfileActivity(mContext, mItem.userId, mItem.nickName);
                }
            }
        });
    }

    private static class MessageHolderBase {
        ImageView userIcon;
        TextView msgDate;
        RelativeLayout rlMsg;
    }

    private static class TextMessageHolder extends MessageHolderBase {
        /**
         * 文字消息体
         */
        GifTextView msg;
    }

    /**
     * 另外一种方法解析表情将[表情]换成fxxx
     *
     * @param message
     *            传入的需要处理的String
     * @return
     */
    private String convertNormalStringToSpannableString(String message) {
        String hackTxt;
        if (message.startsWith("[") && message.endsWith("]")) {
            hackTxt = message + " ";
        } else {
            hackTxt = message;
        }

        Matcher localMatcher = EMOTION_URL.matcher(hackTxt);
        while (localMatcher.find()) {
            String str2 = localMatcher.group(0);
            if (TianYaGongZaiApplication.getInstance().getFaceMap().containsKey(str2)) {
                String faceName = mContext.getResources().getString(
                        TianYaGongZaiApplication.getInstance().getFaceMap().get(str2));
                CharSequence name = options(faceName);
                message = message.replace(str2, name);
            }

        }
        return message;
    }

    /**
     * 取名字f010
     *
     * @param faceName
     */
    private CharSequence options(String faceName) {
        int start = faceName.lastIndexOf("/");
        CharSequence c = faceName.subSequence(start + 1, faceName.length() - 4);
        return c;
    }
}
